package com.neko.seed.util.sms;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author zhaokai
 * @version 1.0
 * @ClassName SMSUtils
 * <p>description 阿里云短信接口工具类
 * @Date 2021-01-25 10:34:58
 */
@Slf4j
@Component
public class SmsUtils {
    /**
     * 阿里云账户的 accessKeyId
     */
    @Value("${aliyun.accessKeyId}")
    private String accessKeyId;
    /**
     * 阿里云账户的 accessKeySecret
     */
    @Value("${aliyun.accessKeySecret}")
    private String accessKeySecret;
    /**
     * 产品域名
     */
    @Value("${aliyun.sms.domain}")
    private String domain;
    /**
     * 短信签名
     */
    @Value("${aliyun.sms.sign}")
    private String signName;
    /**
     * 阿里云regionId
     */
    @Value("${aliyun.oss.regionId}")
    private String regionId;

    /**
     * 生成阿里云短信请求Request
     *
     * @param phone        手机号
     * @param templateCode 短信模板编号
     * @return
     */
    public CommonRequest generateRequest(String phone, String templateCode) {
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(domain);
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", regionId);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("TemplateCode", templateCode);
        return request;
    }


    /**
     * 发送短信
     *
     * @param phone        手机号
     * @param params       模板参数 JSON格式
     * @param templateCode 短信模板编号
     * @return
     */
    public boolean sendSms(String phone, Map<String, Object> params, String templateCode) {
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = generateRequest(phone, templateCode);
        request.putQueryParameter("TemplateParam", JSON.toJSONString(params));
        try {
            CommonResponse response = client.getCommonResponse(request);
            log.info("=====>阿里云短信返回：" + JSON.parseObject(response.getData(), Map.class).get("Message").toString());
            return response.getHttpResponse().isSuccess();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }
}
